<template>
  <!-- 修改密码 -->
  <div class="changePW">
    <el-dialog v-model="state.isShowChangePasswordDialog" title="修改密码" width="400px">
      <el-form class="login-form" :label-position="labelPosition" :rules="rules">
        <el-form-item label="请输入旧密码" prop="oldpassword">
          <el-input v-model="PassWordData.oldpassword" placeholder="旧密码" type="password" />
        </el-form-item>
        <el-form-item label="请输入新密码" prop="newpassword">
          <el-input v-model="PassWordData.newpassword" placeholder="新密码" type="password" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="state.isShowChangePasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="updatePW">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { updatePasswordAPI } from '../../../api/userinfo'
import { useRouter } from 'vue-router'
import { tracking } from '../../../utils/operate'

const router = useRouter()

const labelPosition = ref('top')


const state = reactive({
  isShowChangePasswordDialog: false,
})

const openDialog = () => {
  state.isShowChangePasswordDialog = true
}

interface PassWordData {
  oldpassword: string
  newpassword: string
}


const PassWordData: PassWordData = reactive({
  oldpassword: '',
  newpassword: '',
})

// 表单校验
const rules = reactive({
  oldpassword: [
    { required: true, message: '请输入您想修改的密码', trigger: 'blur' },
  ],
  newpassword: [
    { required: true, message: '请再次确认您的新密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{6,12}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
})


// 修改密码
const updatePW = async () => {

  const res = await updatePasswordAPI({
    id: localStorage.getItem('id'),
    oldPassword: PassWordData.oldpassword,
    newPassword: PassWordData.newpassword
  })
  if (res.data.status == 0) {
    ElMessage({
      message: '修改密码成功',
      type: 'success',
    })
    state.isShowChangePasswordDialog = false
    tracking("系统设置", "修改密码", name, "高级")
    setTimeout(() => {
      router.push('/login')
    }, 2000)
  } else {
    ElMessage({
      message: res.data.message,
      type: 'error',
    })
  }
}

defineExpose({
  openDialog
})
</script>

<style lang="scss" scoped>
:deep(.el-input) {
  width: 100%
}
</style>